<template>
  <Upload
    ref="upload"
    :action="upload_url"
    :on-exceeded-size="handleMaxSize"
    :before-upload="handlebefore"
    :data="{token: token,key:filename}"
    :header="headers"
    :on-success="handleSuccess"
    :show-upload-list="false"
    :with-credentials="false"
  >
    <slot></slot>
  </Upload>
</template>

<script>
import fileapi from "@/api/file";

import { v1 as uuidv1 } from "uuid";

export default {
  name: "FileUpload",
  data() {
    return {
      upload_url: "",
      uploadList: [],
      token: "",
      filename: "",
      headers: {},
      qiniuData: {
        url: "",
        type: ""
      },
    };
  },
  model: {
    prop: "value", 
    event: "hand"
  },
  props: {
    value: String,
    uploaded: Function,
    accept: {
      type: Array,
      default: () => {
        return ["image"];
      }
    }
  },
  created() {},
  methods: {
    uploadURLFromRegionCode(code) {
      var uploadURL = "";
      switch (code) {
        case "ECN":
            uploadURL = "https://up.qiniup.com";
          break;
        case "NCN":
          uploadURL = "https://up-z1.qiniup.com";
          break;
        case "SCN":
          uploadURL = "https://up-z2.qiniup.com";
          break;
        case "NA":
          uploadURL = "https://up-na0.qiniup.com";
          break;
        case "ASG":
          uploadURL = "https://up-as0.qiniup.com";
          break;
        default:
          console.error(
            "please make the region is with one of [ECN, SCN, NCN, NA, ASG]"
          );
      }
      return uploadURL;
    },

    async handlebefore(file) {
      console.log(file.type.split("/")[0]);
      console.log(this.accept);
      let filetype = file.type.split("/")[0];
      if (this.accept.indexOf(filetype) == -1) {
        this.$Message.error("请上传正确的文件类型.");
        return new Promise();
      }
      let _this = this;
      this.$refs.upload.clearFiles(); 
      await fileapi.qiniuToken().then(response => {
        if (response.data.code == 0) {
          console.log(response.data.data);
          let config = response.data.data;
          _this.token = config.token;
          _this.upload_url = _this.uploadURLFromRegionCode(config.address);
        }
      });
      let uuid = uuidv1();
      let ext = file.name.substring(file.name.lastIndexOf("."));
      this.filename = "remind" + uuid + ext; 
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件大小超出限制",
        desc: '文件"' + file.name + '" 超出上传文件大小限制.'
      });
    },
    handleSuccess(response) {
      if (response.code == 0) {
        let url = response.data;
        console.log("当前上传之后的图片地址是" + response.data)
        this.qiniuData.url = url
        fileapi.saveQiniu(this.qiniuData)
        .then((response => {
          if (response.data.code !== 0) {
            this.$Message.error("保存七牛失败")
          }
        }))
        this.$Message.success("上传成功");
        this.$emit("hand", url);
        this.$emit("uploaded", url);
      } else {
        this.$Message.error("上传失败");
      }
    }
  }
};
</script>